<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button onclick="clearCartFn()">清空购物车</button>
    <button onclick="deleteSelectFn()">删除选中商品</button>
    全选：<input onchange="changeAllSelect(this)" type="checkbox" name="" id="select-all">

    <p>
        总价: <span class="count"></span>
    </p>
    <button onclick="payFn()">结算</button>

    <ul class="cart-list">
        <!-- <li>
            <input type="checkbox" name="" id="">
            <h2></h2>
            数量：<input type="number" name="" id="" value="1">
            价格：<span></span>
            <button>删除</button>

        </li> -->
    </ul>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
    <script src="./request.js"></script>
    <script>
        let uid = localStorage.getItem("uid")

        //         ## 结算

        // 行内事件-获取参数-调用 全选  所选 接口，用户id， 重新加载列表
        async function payFn() {
            let cartPayAPI = 'cart/pay';
            let r = await http.post(cartPayAPI, { id: uid });
            console.log(r.data);
            // 点击支付的时候，后端返回一个 付款页面的地址--支付宝
            // location.href = '值'


        }


        // 全选和取消全选
        // --加载 列表的时候，判断一下 所有的购物车数据是否都是被选中，如果是，把全选按钮设置为true
        async function changeAllSelect(ipt) {
            let changeAllSelectAPI = '/cart/select/all';
            let id = uid;//用户id 
            // type 要修改的状态
            console.log(ipt);
            console.log(ipt.checked);
            // 1(选中) \|\| 0(未选中)
            let type = ipt.checked ? 1 : 0;
            let r = await http.post(changeAllSelectAPI, { id, type })
            console.log(r.data);
            loadCartList()


        }

        // 删除所选
        // 行内事件-调用 删除所选 接口，用户id， 重新加载列表
        async function deleteSelectFn() {
            let cartRemoveSelectAPI = '/cart/remove/select';
            let r = await http.get(cartRemoveSelectAPI, { params: { id: uid } });
            console.log(r.data);
            loadCartList()
        }

        // 清空购物车
        async function clearCartFn() {

            if (confirm('确认要清空吗')) {
                let cartClearAPI = '/cart/clear';

                let r = await http.get(cartClearAPI, { params: { id: uid } })
                console.log(r.data);
                loadCartList()
            }



        }


        // 购物车列表
        async function loadCartList() {
            // 调用接口
            let cartListAPI = '/cart/list';
            let uid = localStorage.getItem('uid');
            let r = await http.get(cartListAPI, { params: { id: uid } })
            console.log(r.data);
            // 循环遍历 拼接字符串
            let liStr = r.data.cart.map(v => `
                <li>
                    <input onchange="changeSelectFn(${v.goods_id})" type="checkbox" name="" id="" ${v.is_select ? 'checked' : ''}>
                    <h2>${v.title}</h2>
                    数量：<input onchange="changeNum(${v.goods_id},this)" type="number" name="" id="" value="${v.cart_number}">
                    价格：<span>${v.current_price}</span>
                    小计:${v.current_price * v.cart_number}
                    <button onclick="delFn(${v.goods_id})">删除</button>

                </li>
            `).join('');
            document.querySelector(".cart-list").innerHTML = liStr

            // --加载 列表的时候，判断一下 所有的购物车数据是否都是被选中，如果是，把全选按钮设置为true
            console.log(r.data.cart);
            let isselectAll = r.data.cart.every(v => v.is_select == true);
            document.querySelector('#select-all').checked = isselectAll

            // 计算总价
            // 获取所有被选中商品--isSelect为true的元素
            let selectedArr = r.data.cart.filter(v => v.is_select == true);
            console.log(selectedArr);

            // let sum = 0;
            // selectedArr.forEach(v => {
            //     sum = sum + v.current_price * v.cart_number;

            // });
            // console.log(sum.toFixed(2));

            let sum = selectedArr.reduce((sum, v) => sum + v.cart_number * v.current_price, 0)
            console.log(sum.toFixed(2));

            document.querySelector('.count').innerHTML = sum.toFixed(2)


        }

        loadCartList()

        // 行内事件- 点击获取删除接口需要使用参数，调用删除接口--重新加载列表

        async function delFn(goodsId) {
            if (confirm('确定要删除')) {
                // goodsId--
                // id 用户id 本地
                let cartRemoveAPI = '/cart/remove'
                let id = localStorage.getItem('uid');
                // 删除接口需要 商品id 和 用户id
                // 一旦-接口出问题---报错-- 看network  请求地址-请求方式-请求参数--和接口文档是否一致
                let r = await http.get(cartRemoveAPI, { params: { id, goodsId } });
                console.log(r.data);
                // 重新加载列表
                loadCartList()
            }


        }

        /* 
        修改商品数量
        
            行内事件，-<input onchange="changeNum()" 

            change 的时候，
            获取当前输入框的值，
            用户 id，
            商品id，
            调用修改接口-重新加载列表
        
        */
        async function changeNum(goodsId, ipt) {
            // 用户 id，
            let uid = localStorage.getItem('uid')
            console.log(goodsId);
            console.log(uid);

            // ipt 触发change事件的input
            console.log(ipt.value);

            // 调用修改接口-重新加载列表
            let cartUpdateNumAPI = '/cart/number';
            let r = await http.post(cartUpdateNumAPI, { id: uid, number: ipt.value, goodsId })
            console.log(r.data);;
            loadCartList()



        }


        /*
        ## 购物车修改选中状态

行内事件，change事件，
<input onchange="changeSelectFn(${v.goods_id})" 


用户 id，商品id，调用修改选中状态接口-重新加载列表
        
        */
        async function changeSelectFn(goodsId) {
            let uid = localStorage.getItem('uid');
            let cartSelectAPI = '/cart/select'
            // 调用接口
            let r = await http.post(cartSelectAPI, { id: uid, goodsId });
            console.log(r.data);
            loadCartList()

        }




    </script>

</body>

</html>